package com.ziiwee.reduce.rest.condition.parser;

import com.ziiwee.reduce.commons.utils.BeanUtil;
import com.ziiwee.reduce.commons.utils.StringUtil;
import com.ziiwee.reduce.rest.utils.JsonUtil;

import java.lang.reflect.Field;

/**
 * @author ziiwee
 * @since 2021/3/12
 */
public abstract class AbstractConditionParser implements ConditionParser<String> {

    protected Class<?> modelType;

    public AbstractConditionParser(Class<?> modelType) {
        this.modelType = modelType;
    }

    protected Comparable castComparable(String name, String value) {
        if (!StringUtil.hasLength(value)) {
            return null;
        }
        return (Comparable) castValue(name, value);
    }

    /**
     * 转换字段值类型
     *
     * @param name     字段名
     * @param objValue 字段值
     * @return
     */
    protected Object castValue(String name, Object objValue) {
        try {
            if (objValue == null) {
                return null;
            }
            String value = objValue.toString().trim();
            Field field = BeanUtil.getField(modelType, name);
            if (field == null) {
                throw new ConditionParserException("字段不存在：" + name);
            }
            Class<?> type = field.getType();
            Object castValue = JsonUtil.castValue(type, value);
            if (castValue != null) {
                return castValue;
            }
            throw new ConditionParserException("无法解析的值：" + name + "=" + value);
        } catch (Exception e) {
            throw new ConditionParserException(String.format("无法解析的值: %s=%s :%s", name, objValue, e.getMessage()), e);
        }
    }
}
